<template>
   <div>
      <div style="display: flex; justify-content: space-between">
         <el-breadcrumb
            separator-class="el-icon-arrow-right"
            style="margin-top: 12px; margin-left: 26px"
         >
            <el-breadcrumb-item>
               <span style="color: #409eff; font-size: 15px">招生省份信息</span>
            </el-breadcrumb-item>
         </el-breadcrumb>

         <div style="display: flex">
            <div
               style="
                  margin-top: 3px;
                  margin-right: 14px;
                  display: flex;
                  width: 450px;
               "
            >
               <div style="flex: 1">
                  <span style="vertical-align: middle; font-size: 15px"
                     >年份：</span
                  >
                  <el-select
                     v-model="selectConditions.grade"
                     placeholder="Select"
                     style="width: 100px;"
                  >
                     <el-option
                        v-for="item in selectItems.grade"
                        :key="item"
                        :label="item"
                        :value="item"
                     />
                  </el-select>
               </div>

               <div style="flex: 2">
                  <span style="vertical-align: middle; font-size: 15px"
                     >专业：</span
                  >
                  <el-select
                     v-model="selectConditions.major"
                     placeholder="Select"
                     style="width: 200px;"
                  >
                     <el-option
                        v-for="item in selectItems.major"
                        :key="item"
                        :label="item"
                        :value="item"
                     />
                  </el-select>
               </div>
            </div>

            <el-button
               style="margin-right: 15px"
               @click="provinceDataVisuable()"
               v-if="
                  currentPagePermissionStatusByCurrentUser.dataVisibleProvide
               "
            >
               <el-icon style="margin-right: 4px; vertical-align: middle">
                  <VideoCamera />
               </el-icon>
               数据可视化
            </el-button>

            <el-button
               style="margin-right: 15px"
               @click="downloadProvinceDataFile"
               v-if="
                  currentPagePermissionStatusByCurrentUser.exportCurrentPageData
               "
            >
               <el-icon style="margin-right: 4px; vertical-align: middle">
                  <Crop />
               </el-icon>
               导出本页列表数据
            </el-button>

            <el-button
               style="margin-right: 15px"
               @click="editBatchProvinceAdmissionScore()"
               v-if="
                  currentPagePermissionStatusByCurrentUser.operateProvinceList
               "
            >
               <el-icon style="margin-right: 4px; vertical-align: middle">
                  <Document />
               </el-icon>
               批量编辑省份一本线
            </el-button>
         </div>
      </div>

      <!-- 招生省份数据列表 -->
      <div style="margin-top: 30px">
         <h1 style="margin-bottom: 10px">
            {{ selectConditions.grade }}年
            {{ selectConditions.major }} 专业生源高考成绩情况统计
         </h1>
         <el-table
            style="border-radius: 10px"
            :data="enrollmentProviceData"
            stripe
            :header-cell-style="{ height: '60px', fontSize: '16px' }"
            :cell-style="{ height: '60px', fontSize: '14px' }"
            :default-expand-all="false"
         >
            <el-table-column
               prop="province"
               label="省份"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>

            <el-table-column
               prop="admissionScore"
               label="本科一批分数线"
               header-align="center"
               min-width="130"
               align="center"
            ></el-table-column>

            <el-table-column
               prop="averageScoreByCollege"
               label="学院平均分数"
               header-align="center"
               min-width="120"
               align="center"
            ></el-table-column>

            <el-table-column
               prop="averageScoreByMajor"
               label="专业平均分数"
               header-align="center"
               min-width="120"
               align="center"
            ></el-table-column>

            <el-table-column
               prop="highestScoreByCollege"
               label="学院最高分"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>

            <el-table-column
               prop="highestScoreByMajor"
               label="专业最高分"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>

            <el-table-column
               prop="lowestScoreByCollege"
               label="学院最低分"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>

            <el-table-column
               prop="lowestScoreByMajor"
               label="专业最低分"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>

            <el-table-column
               prop="studentNum"
               label="学生数量"
               header-align="center"
               min-width="100"
               align="center"
            ></el-table-column>

            <el-table-column
               label="操作"
               width="100px"
               header-align="center"
               min-width="100"
               align="center"
               v-if="
                  currentPagePermissionStatusByCurrentUser.operateProvinceList
               "
            >
               <template v-slot="scope">
                  <el-tooltip
                     effect="dark"
                     content="编辑本科一批分数线"
                     placement="top-start"
                  >
                     <el-icon
                        @click="editAdmissionScore(scope.row)"
                        style="font-size: 21px; color: #5a9cf8; cursor: pointer"
                        ><Edit
                     /></el-icon>
                  </el-tooltip>
               </template>
            </el-table-column>
         </el-table>
      </div>

      <!-- 编辑本科一批分数线窗口 -->
      <el-dialog
         v-model="editAdmissionScoreDialogShow"
         width="500px"
         :showClose="false"
         style="border-radius: 4px"
      >
         <template #header>
            <span style="font-size: 18px">{{
               "编辑 " +
               admissionScoreEditForm.grade +
               " 年 " +
               admissionScoreEditForm.province +
               " 本科一批分数线"
            }}</span>
         </template>

         <el-form :model="admissionScoreEditForm">
            <el-form-item
               style="margin-left: -50px"
               label="分数线"
               label-width="100"
               prop="admissionScore"
            >
               <el-input
                  style="width: 380px"
                  v-model="admissionScoreEditForm.admissionScore"
                  placeholder="请输入分数："
               ></el-input>
            </el-form-item>
         </el-form>

         <template #footer>
            <el-button @click="editAdmissionScoreDialogShow = false"
               >取 消</el-button
            >
            <el-button type="primary" @click="confimEditAdmissionScore()"
               >修 改</el-button
            >
         </template>
      </el-dialog>

      <!-- 批量编辑本科一批分数线窗口 -->
      <el-dialog
         v-model="editAdmissionScoreBatchDialogShow"
         width="500px"
         :showClose="false"
         style="border-radius: 4px"
      >
         <template #header>
            <span style="font-size: 18px">{{
               "编辑 " + selectConditions.grade + " 年本科一批分数线"
            }}</span>
         </template>

         <el-form :model="provinceAdmissionScore">
            <el-form-item
               v-for="item in provinceAdmissionScore"
               :key="item.id"
               style="margin-left: -50px"
               :label="item.province"
               label-width="100"
               prop="admissionScore"
            >
               <el-input
                  style="width: 380px"
                  v-model="item.admissionScore"
                  placeholder="请输入分数："
               ></el-input>
            </el-form-item>
         </el-form>

         <template #footer>
            <el-button @click="editAdmissionScoreBatchDialogShow = false"
               >取 消</el-button
            >
            <el-button type="primary" @click="confirmEditBatchAdmissionScore()"
               >修 改</el-button
            >
         </template>
      </el-dialog>

      <el-dialog
         v-model="dataVisualizationDialogShow"
         width="1000px"
         style="border-radius: 4px; position: relative"
      >
         <h1 style="margin-top: -38px; margin-bottom: 20px; font-size: 19px">
            <el-button
               style="left: 12px; top: 20px; position: absolute"
               @click="showCollegeScoreEchartsContainer()"
               >学院招生分数详情</el-button
            >
            计算机学院 {{ selectConditions.grade }} 年
            {{ selectConditions.major }}
         </h1>
         <div
            style="height: 400px; width: 100%; margin-top: -10px"
            ref="scoreEchartsContainerDom"
         ></div>

         <h1
            v-show="collegeScoreEchartsContainerShow"
            style="
               margin-top: -2px;
               margin-bottom: 20px;
               font-size: 19px;
               position: relative;
            "
         >
            计算机学院 {{ selectConditions.grade }} 年全专业招生分数
         </h1>

         <div
            v-show="collegeScoreEchartsContainerShow"
            style="height: 400px; width: 100%; margin-top: -10px"
            ref="collegeScoreEchartsDom"
         ></div>
      </el-dialog>
   </div>
</template>

<script>
import $axios from "@/axios";
import { useStore } from "vuex";
import router from "@/rooter";
import { nextTick, onMounted, reactive, ref, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import * as echarts from "echarts";

export default {
   name: "EnrollmentProvice",
   setup() {
      const store = useStore();
      // 招生省份数据
      let enrollmentProviceData = ref([]);

      // 当前页当前用户权限
      let currentPagePermissionStatusByCurrentUser = reactive({
         pageShow: false,
         operateProvinceList: false,
         dataVisibleProvide: false,
         exportCurrentPageData: false,
      });

      // 下拉表可选择内容
      let selectItems = reactive({
         major: [
            "计算机科学与技术",
            "软件工程",
            "网络工程",
            "大数据与数据科学",
         ],
         grade: [
            "2014",
            "2015",
            "2016",
            "2017",
            "2018",
            "2019",
            "2020",
            "2021",
            "2022",
            "2023",
         ],
      });

      // 下拉列表选择的内容
      let selectConditions = reactive({
         college: "计算机学院",
         major: "计算机科学与技术",
         // grade: new Date().getFullYear() - 1,
         grade: "2020",
      });

      let editAdmissionScoreDialogShow = ref(false);

      // 本科一批分数线修改表单
      let admissionScoreEditForm = ref({
         id: "",
         admissionScore: "",
         province: "",
         grade: "",
      });

      function editAdmissionScore(row) {
         editAdmissionScoreDialogShow.value = true;

         for (let item in admissionScoreEditForm.value) {
            admissionScoreEditForm.value[item] = row[item];
         }

         console.log(row);
         console.log(admissionScoreEditForm.value);
      }

      function confimEditAdmissionScore() {
         if (
            admissionScoreEditForm.value.admissionScore === null ||
            admissionScoreEditForm.value.admissionScore === ""
         ) {
            editAdmissionScoreDialogShow.value = false;
            return;
         } else {
            let num = parseInt(admissionScoreEditForm.value.admissionScore);
            if (!isNaN(num)) {
               admissionScoreEditForm.value.admissionScore = parseInt(
                  admissionScoreEditForm.value.admissionScore
               );

               $axios
                  .post(
                     "/province/updateProvinceAdmissionScore",
                     admissionScoreEditForm.value
                  )
                  .then(() => {
                     ElMessage({
                        type: "success",
                        message: "分数线更新成功",
                        duration: 1500,
                     });

                     setTimeout(() => {
                        window.location.reload();
                     }, 800);
                  });
            } else {
               ElMessage({
                  type: "error",
                  message: "请输入数字",
                  duration: 1000,
               });
            }
         }
      }

      // ======================== 导出数据
      function downloadProvinceDataFile() {
         ElMessageBox.confirm("是否导出本页省份列表数据？", "Warning", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
            draggable: true,
         }).then(() => {
            if (enrollmentProviceData.value.length <= 0) {
               ElMessage({
                  type: "error",
                  message: "暂无数据",
                  duration: 1500,
               });
            } else {
               $axios
                  .post(
                     "/file/downloadProvinceDataFile",
                     enrollmentProviceData.value,
                     {
                        responseType: "blob",
                     }
                  )
                  .then((response) => {
                     const url = window.URL.createObjectURL(
                        new Blob([response.data])
                     );
                     const link = document.createElement("a");
                     link.href = url;
                     link.setAttribute("download", "college.xlsx");
                     document.body.appendChild(link);
                     link.click();

                     ElMessage({
                        type: "success",
                        message: "导出成功，请等待下载完成",
                        duration: 2000,
                     });
                  });
            }
         });
      }

      // 监听选择条件的变化
      watch(selectConditions, (newValue, oldValue) => {
         // 发送请求，获取指定专业,指定年份的招生省份信息
         $axios
            .post("/province/getProvinceEnrollment", newValue)
            .then((resp) => {
               enrollmentProviceData.value = resp.data.data;
            });
      });

      let editAdmissionScoreBatchDialogShow = ref(false);

      let provinceAdmissionScore = ref([]);

      function editBatchProvinceAdmissionScore() {
         editAdmissionScoreBatchDialogShow.value = true;
         provinceAdmissionScore.value = [];

         for (let index in enrollmentProviceData.value) {
            let id = enrollmentProviceData.value[index].id;
            let province = enrollmentProviceData.value[index].province;
            let admissionScore =
               enrollmentProviceData.value[index].admissionScore;
            let grade = enrollmentProviceData.value[index].grade;

            provinceAdmissionScore.value.push({
               id,
               province,
               admissionScore,
               grade,
            });
         }
      }

      function confirmEditBatchAdmissionScore() {
         let changed = false;

         for (let index in provinceAdmissionScore.value) {
            if (
               provinceAdmissionScore.value[index].admissionScore !==
               enrollmentProviceData.value[index].admissionScore
            ) {
               changed = true;
            }
         }

         if (changed) {
            // 发送请求
            $axios
               .post(
                  "/province/editAdmissionScoreBatch",
                  provinceAdmissionScore.value
               )
               .then((resp) => {
                  ElMessage({
                     message: "修改成功",
                     type: "success",
                     duration: 1000,
                  });

                  setTimeout(() => {
                     window.location.reload();
                  }, 800);
               });
         } else {
            ElMessage({
               message: "未修改任何内容",
               type: "info",
               duration: 1000,
            });
         }
      }

      // ======================== 数据可视化
      let dataVisualizationDialogShow = ref(false);

      function provinceDataVisuable() {
         dataVisualizationDialogShow.value = true;
         collegeScoreEchartsContainerShow.value = false;
         scoreEchartsContainerInit();
      }

      // 专业分数图
      let scoreEchartsContainerDom = ref(null);

      // 学院分数图
      let collegeScoreEchartsContainerShow = ref(false);
      let collegeScoreEchartsDom = ref(null);

      let tempChartMain = null;

      function scoreEchartsContainerInit() {
         nextTick(() => {
            if (tempChartMain) {
               tempChartMain.dispose();
            }

            tempChartMain = echarts.init(scoreEchartsContainerDom.value);

            let source = [
               [
                  "product",
                  "专业最高分",
                  "学院最高分",
                  "专业平均分",
                  "学院平均分",
                  "专业最低分",
                  "学院最低分",
                  "招生人数",
               ],
            ];

            for (let item of enrollmentProviceData.value) {
               source.push([
                  item.province,
                  item.highestScoreByMajor,
                  item.highestScoreByCollege,
                  item.averageScoreByMajor,
                  item.averageScoreByCollege,
                  item.lowestScoreByMajor,
                  item.lowestScoreByCollege,
                  item.studentNum,
               ]);
            }

            let option = {
               legend: {
                  data: [
                     "专业最高分",
                     "学院最高分",
                     "专业平均分",
                     "学院平均分",
                     "专业最低分",
                     "学院最低分",
                     "招生人数",
                  ],
                  selected: {
                     学院最高分: false,
                     学院平均分: false,
                     学院最低分: false,
                  },
               },
               tooltip: {},
               toolbox: {
                  show: true,
                  feature: {
                     saveAsImage: {},
                  },
               },
               dataset: {
                  source,
               },
               dataZoom: [
                  {
                     show: true,
                  },
               ],
               xAxis: { type: "category" },
               yAxis: [
                  {
                     type: "value",
                     name: "专业分数",
                     axisLabel: {
                        formatter: "{value} 分",
                     },
                  },
                  {
                     type: "value",
                     name: "招生人数",
                     axisLabel: {
                        formatter: "{value} 人",
                     },
                  },
               ],
               series: [
                  { type: "bar" },
                  { type: "bar" },
                  { type: "bar" },
                  { type: "bar" },
                  { type: "bar" },
                  { type: "bar" },
                  { type: "line", name: "招生人数", yAxisIndex: 1 },
               ],
            };

            tempChartMain.setOption(option);
         });
      }

      function showCollegeScoreEchartsContainer() {
         if (collegeScoreEchartsContainerShow.value) {
            collegeScoreEchartsContainerShow.value = false;
            return;
         }

         collegeScoreEchartsContainerShow.value = true;

         collegeScoreEchartsContainerInit();
      }

      let tempChart = null;

      function collegeScoreEchartsContainerInit() {
         nextTick(() => {
            if (tempChart) {
               tempChart.dispose();
            }

            tempChart = echarts.init(collegeScoreEchartsDom.value);

            let source = [
               ["product", "学院最高分", "学院平均分", "学院最低分"],
            ];

            for (let item of enrollmentProviceData.value) {
               source.push([
                  item.province,
                  item.highestScoreByCollege,
                  item.averageScoreByCollege,
                  item.lowestScoreByCollege,
               ]);
            }

            let option = {
               legend: {},
               tooltip: {},
               toolbox: {
                  show: true,
                  feature: {
                     saveAsImage: {},
                  },
               },
               dataset: {
                  source,
               },
               dataZoom: [
                  {
                     show: true,
                  },
               ],
               xAxis: { type: "category" },
               yAxis: [
                  {
                     type: "value",
                     name: "学院分数",
                     axisLabel: {
                        formatter: "{value} 分",
                     },
                  },
               ],
               series: [{ type: "bar" }, { type: "bar" }, { type: "bar" }],
            };

            tempChart.setOption(option);
         });
      }

      // 等待vuex中的userPermission准备好
      function waitForPermissions() {
         return new Promise((resolve) => {
            store.watch(
               () => store.state.currentLoginUser.permissions,
               (newValue) => {
                  // 权限：
                  if (newValue) {
                     newValue.forEach((permission) => {
                        if (
                           permission.permissionPath === "/enrollmentProvince"
                        ) {
                           currentPagePermissionStatusByCurrentUser.pageShow = true;
                        }
                     });

                     newValue.forEach((permission) => {
                        if (
                           permission.permissionPath ===
                           "/enrollmentProvince/operateProvinceList"
                        ) {
                           currentPagePermissionStatusByCurrentUser.operateProvinceList = true;
                        }
                     });

                     newValue.forEach((permission) => {
                        if (
                           permission.permissionPath ===
                           "/enrollmentProvince/dataVisible"
                        ) {
                           currentPagePermissionStatusByCurrentUser.dataVisibleProvide = true;
                        }
                     });

                     newValue.forEach((permission) => {
                        if (
                           permission.permissionPath ===
                           "/enrollmentProvince/exportProvinceFile"
                        ) {
                           currentPagePermissionStatusByCurrentUser.exportCurrentPageData = true;
                        }
                     });

                     // 将 Promise 状态改为已完成
                     resolve();
                  }
               },
               {
                  immediate: true, // 立即监听
               }
            );
         });
      }

      onMounted(async () => {
         await waitForPermissions();

         if (!currentPagePermissionStatusByCurrentUser.pageShow) {
            ElMessage({
               type: "error",
               message: "用户无权限",
               duration: 1500,
            });
            router.go(-1);
            return;
         }

         // 发送请求，获取指定专业,指定年份的招生省份信息
         $axios
            .post("/province/getProvinceEnrollment", selectConditions)
            .then((resp) => {
               enrollmentProviceData.value = resp.data.data;
            });
      });

      return {
         enrollmentProviceData,
         selectItems,
         selectConditions,
         editAdmissionScore,
         editAdmissionScoreDialogShow,
         admissionScoreEditForm,
         confimEditAdmissionScore,
         downloadProvinceDataFile,
         editAdmissionScoreBatchDialogShow,
         editBatchProvinceAdmissionScore,
         provinceAdmissionScore,
         confirmEditBatchAdmissionScore,
         provinceDataVisuable,
         dataVisualizationDialogShow,
         scoreEchartsContainerDom,
         collegeScoreEchartsContainerShow,
         collegeScoreEchartsDom,
         collegeScoreEchartsContainerInit,
         showCollegeScoreEchartsContainer,
         currentPagePermissionStatusByCurrentUser,
      };
   },
};
</script>

<style>
</style>